package com.zhike.b2b.html.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.zhike.b2b.html.IHtmlService;
import com.zhike.b2b.model.ClassVo;
import com.zhike.b2b.model.ProductClassVo;
import com.zhike.b2b.sysparam.IParamService;
import freemarker.template.Configuration;
import freemarker.template.Template;

@Service
public class HtmlService implements IHtmlService {
	
	protected IParamService ps;
	
	protected JdbcTemplate jt;
	
	 @Resource
	 public void setPs(IParamService ps) {
		this.ps = ps;
	 }

	 @Resource
	public void setDataSource(DataSource dataSource) {
		jt = new JdbcTemplate(dataSource);
	}
	/**
	 * 生成静态页面主方法
	 * 
	 * @param context
	 *            ServletContext
	 * @param data
	 *            一个Map的数据结果集
	 * @param templatePath
	 *            ftl模版路径
	 * @param targetHtmlPath
	 *            生成静态页面的路径
	 */
	public void crateHTML(ServletContext context, Map<String, Object> data,
			String templatePath, String targetHtmlPath) {
		Configuration freemarkerCfg = new Configuration();
		// 加载模版
		freemarkerCfg.setServletContextForTemplateLoading(context, "/");
		freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
		freemarkerCfg.setNumberFormat("#");
		Writer out = null;
		try {
			// 指定模版路径
			Template template = freemarkerCfg
					.getTemplate(templatePath, "UTF-8");
			template.setEncoding("UTF-8");
			// 静态页面路径
			String htmlPath = context.getRealPath("/") + "/" + targetHtmlPath;
			String dirStr = htmlPath.substring(0, htmlPath.lastIndexOf("/"));
			File dir = new File(dirStr);
			if(!dir.exists())
				dir.mkdirs();
			File htmlFile = new File(htmlPath);
			
			out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(htmlFile), "UTF-8")));
			// 处理模版
			template.process(data, out);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	  /**
	   * 获取系统中所有的模板根类别
	   * @return
	   */
      public List<ClassVo> getRootModels()
	  {
    	  List<ClassVo> lcv = new ArrayList<ClassVo>();
    	  lcv.add(new ClassVo("100","产品供应[供应模型]","prod"));
    	  lcv.add(new ClassVo("100","求购[求购模型]","buy"));
    	  lcv.add(new ClassVo("100","资讯[资讯模型]","news"));
    	  lcv.add(new ClassVo("100","展会[资讯模型]","expo"));
    	  lcv.add(new ClassVo("100","企业[企业模型]","com"));
    	  lcv.add(new ClassVo("100","招聘[人才模型]","job"));
    	  lcv.add(new ClassVo("100","求职[求职模型]","apply"));
    	  lcv.add(new ClassVo("100","服务[服务模型]","serv"));
    	  return lcv;
	  }
      /**
       * 获取各类别的子类
       * @param clzTblName
       * @param clzId
       * @return
       */
      public List<ClassVo> getClassInfoByParent(String clzTblName, String clzId,final String type)
      {
        StringBuffer buff = new StringBuffer("select class_id,class_name,list_model,index_model,content_model,store_path,list_rule,article_rule,home_name from " + clzTblName + " where 1=1 ");
        int len = clzId.length();
        int i = 3;
        switch (len)
        {
        case 0:
          i = 3;
          break;
        case 3:
          i = 6;
          break;
        case 6:
          i = 10;
          break;
        case 10:
          i = 15;
          break;
       }
        if (!clzId.equals("000"))
          buff.append(" and class_id like '" + clzId + "%'");
        buff.append(" and length(class_id)=" + i + " and remove_tag='1'");
        List<ClassVo> lpcv = jt.query(buff.toString(),  new RowMapper<ClassVo>() {
			 public ClassVo mapRow(ResultSet rs, int rowNum)
				throws SQLException {
				 ClassVo pcv = new ProductClassVo();
				 pcv.setClassId(rs.getString("class_id"));
				 pcv.setClassName(rs.getString("class_name"));
				 pcv.setClassType(type);
				 return pcv;
			}});
         return lpcv;
      }
	
	/**
	 * 获取底部信息
	 * @param data
	 */
	public void getFooterInfo(Map<String,Object> data)
	{
		data.put("helpCenter", ps.getParamValue("help_center"));
		data.put("serviceTel", ps.getParamValue("service_tel"));
		data.put("faxTel", ps.getParamValue("fax_tel"));
		data.put("servQq", ps.getParamValue("QQ"));
		data.put("copyright", ps.getParamValue("copyright"));
	}
}
